package com.hqyj.javaSpringBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter
public class ParameterFilter implements Filter {

    private final static Logger LOGGER= LoggerFactory.getLogger(ParameterFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==========init filter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==========do filter");
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        HttpServletResponse httpRespone=(HttpServletResponse)response;

        HttpServletRequestWrapper requestWrapper=new HttpServletRequestWrapper(httpRequest){
            /**拦截通过request传入的值*/
            @Override
            public String getParameter(String name) {
                String value=super.getParameter(name);
                if (StringUtils.isBlank(value)){
                    return "";
                }else {
                    return value.replaceAll("fack","****");
                }
            }
            /**拦截通过注释获取的值*/
            @Override
            public String[] getParameterValues(String name) {
                String[] values=super.getParameterValues(name);
                List<String> str=new ArrayList<>();
                for (String value : values) {
                    str.add(value.replaceAll("fack","***"));
                }
                return str.toArray(new String[str.size()]);
            }
        };

        /**放行*/
        chain.doFilter(requestWrapper,httpRespone);
    }

    @Override
    public void destroy() {
        LOGGER.debug("========== destroy filter");
    }
}
